Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Types of Inheritance

Single Inheritance

Single inheritance is a fundamental concept in Java’s Object-Oriented Programming (OOP) where a class, known as a subclass, inherits the properties and methods of a single parent class, known as the superclass. This type of inheritance is simple to understand and it follows an is-a relationship. single inheriatance Here’s the syntax for single inheritance in Java:
Single inheritance basic structure class SuperClass { // members } class SubClass extends SuperClass { // members }
In this syntax, SubClass is the class that is extending SuperClass. This means that SubClass inherits all the non-private members (fields and methods) of SuperClass. Here’s an example of single inheritance in Java:
Single inheritance basic example class Employee { float salary = 34534 * 12; } // change filename as Executive.java public class Executive extends Employee { float bonus = 3000 * 6; public static void main(String args[]) { Executive obj = new Executive(); System.out.println("Total salary credited: " + obj.salary); System.out.println("Bonus of six months: " + obj.bonus); } }

Output

Total salary credited: 414408.0 Bonus of six months: 18000.0
Example for single inheritance from superclass Animal // Superclass class Animal { public void eat() { System.out.println("Animal is eating..."); } } // Subclass // change filename as Dog.java public class Dog extends Animal { public void bark() { System.out.println("Dog is barking..."); } public static void main(String[] args) { Dog dog = new Dog(); dog.eat(); // method from Animal class dog.bark(); // method from Dog class } }

Output

Animal is eating... Dog is barking...
In this example, Dog is a subclass that extends the Animal superclass. The Dog class inherits the eat() method from the Animal class, and it also defines its own method bark(). In the main method, an object dog of type Dog is created. This object can call both the eat() method and the bark() method. This is a simple demonstration of how single inheritance works in Java. It allows for code reusability and reduces code duplication.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ inheritance ★ single inheritance

Tutorials